package com.example.common_base.net;

import android.accounts.NetworkErrorException;
import android.util.Log;

import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class HttpObserver<T> extends DisposableObserver<T> {

    //    private static final String TAG = "Request";
    private HttpSuccessListener<T> mSuccessListener;
    private HttpErrorListener mErrorListener;
//    private static QMUITipDialog loadingDialog;


    public HttpObserver() {
    }


    public HttpObserver(HttpSuccessListener<T> successListener) {
        if (successListener == null) {
            throw new NullPointerException("HttpSuccessListener not null");
        } else {
            this.mSuccessListener = successListener;
        }
    }


    public HttpObserver(HttpSuccessListener<T> successListener, HttpErrorListener errorListener) {
        if (successListener == null) {
            throw new NullPointerException("HttpSuccessListener not null");
        } else if (errorListener == null) {
            throw new NullPointerException("HttpErrorListener not null");
        } else {
            this.mSuccessListener = successListener;
            this.mErrorListener = errorListener;
        }
    }


    @Override
    public void onNext(T t) {
        try {
            this.mSuccessListener.success(t);
        } catch (Exception exception) {
            exception.printStackTrace();
            this.mErrorListener.error(new Throwable("数据解析异常"));
        }
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof NetworkErrorException || e instanceof UnknownHostException || e instanceof ConnectException) {
            //连接地址或者断网
            Throwable da = new Throwable("请检查网络连接是否畅通");
            this.mErrorListener.error(da);
        } else if (e instanceof InterruptedIOException || e instanceof TimeoutException) {
            Throwable da = new Throwable("请求超时");
            this.mErrorListener.error(da);
        }
//        else if (e instanceof ApiException) {
//            EventBus.getDefault().post(new BaseEventData<>(Flag.Event.JUMP_LOGIN));
//        }
        else if (this.mErrorListener != null) {
            Log.e("http_loge", e.getMessage().toString());
            this.mErrorListener.error(e);
        }
    }

    @Override
    public void onComplete() {

    }


    public static <T> ObservableTransformer<T, T> schedulers() {
        return upstream -> upstream.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }


}
